//
//  CircleProgressView.swift
//  PhotoBrowser
//
//  Created by meng on 16/5/22.
//  Copyright © 2016年 leotao. All rights reserved.
//

import UIKit

let width:CGFloat = 100;
let height:CGFloat = 100;

class CircleProgressView: UIView {
    var circleLineLayer = CAShapeLayer();
    var circleLayer = CAShapeLayer();
    
    var progress: CGFloat = 0 {
        didSet {
            if progress == 0 {
                progress = 0.05;
            }
            
            if progress < 1 {
                self.hidden = false;
            } else {
                self.hidden = true;
            }
            
            circleLayer.path = fillPath(progress).CGPath;
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame);
        
        circleLayer.fillColor = UIColor.whiteColor().colorWithAlphaComponent(0.6).CGColor;
        circleLayer.strokeColor = nil;
        
        circleLineLayer.fillColor = UIColor.blackColor().colorWithAlphaComponent(0.5).CGColor;
        circleLineLayer.strokeColor = UIColor.whiteColor().colorWithAlphaComponent(0.6).CGColor;
        
        
        self.layer.addSublayer(circleLayer);
        self.layer.addSublayer(circleLineLayer);
        
        self.hidden = true;
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func showInView(view: UIView) {
        let rect = CGRectMake((view.bounds.width - width) * 0.5, (view.bounds.height - height) * 0.5, width, height);
        self.frame = rect;
        view.addSubview(self);
        view.hidden = false;
    }
    
    func fillPath(progress: CGFloat) -> UIBezierPath {
        let startAngle = -(1.0 / 2) * CGFloat(M_PI);
        let endAngle = startAngle + progress * CGFloat(M_PI) * 2;
        let radius = min(bounds.width, bounds.height) / 2 - 4;
        let center = CGPointMake(bounds.width * 0.5, bounds.height * 0.5);
        
        let fillPath = UIBezierPath(arcCenter: center, radius: radius, startAngle: -(1.0 / 2) * CGFloat(M_PI), endAngle: endAngle, clockwise: true);
        fillPath.addLineToPoint(center);
        fillPath.closePath();
        
        return fillPath;
    }
    
    override func layoutSubviews() {
        super.layoutSubviews();
        
        circleLineLayer.frame = self.bounds;
        circleLayer.frame = self.bounds;
        
        let radius = min(bounds.width, bounds.height) / 2 - 2;
        let center = CGPointMake(bounds.width * 0.5, bounds.height * 0.5);
        let strokePath = UIBezierPath(arcCenter: center, radius: radius, startAngle: -(1.0 / 2) * CGFloat(M_PI), endAngle: (3.0 / 2) * CGFloat(M_PI), clockwise: true);
        
        circleLineLayer.path = strokePath.CGPath;
        
        
    }
}
